﻿#include "clientfile.h"
#include "ui_clientfile.h"
#include<QDebug>
#include<QMessageBox>
#include<QHostAddress>

clientfile::clientfile(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::clientfile)
{
    ui->setupUi(this);

    //设置皮肤
    setfacer(4);
    tcpsocket=new QTcpSocket(this);
    setWindowTitle(QString::fromLocal8Bit("客户端"));
    this->setWindowIcon(QIcon(":/photo/11.jfif"));
    isStart=true;

    connect(tcpsocket,&QTcpSocket::readyRead,[=](){

      QByteArray buf=  tcpsocket->readAll();
        //取出接收的内容
        if(isStart==true){
            //接收头
            isStart=false;
            //解析头部信息 拆包 初始化
            filename=QString(buf).section("##",0,0);
            filesize=QString(buf).section("##",1,1).toInt();
            recvesize=0;

            //打开文件
            file.setFileName(filename);
            bool isok=file.open(QIODevice::WriteOnly);
            if(isok==false){
                qDebug()<<"Write Only!";
            }
        }
        else{
            qint64 len=file.write(buf);
            recvesize+=len;
            if(recvesize==filesize){
                file.close();
                QMessageBox::information(this,QString::fromLocal8Bit("完成"),QString::fromLocal8Bit("文件接收完成"));
                tcpsocket->disconnectFromHost();
                tcpsocket->close();
            }
        }

    });
}

void clientfile::setfacer(int index)
{
    //换背景
    QImage _image;   //创建image
   //利用字符串拼接 完成photo
    QString str=QString(":/photo/back%1.jpg").arg(index);
   _image.load(str);
   setAutoFillBackground(true);   // 这个属性一定要设置
    QPalette pal(palette());
     pal.setBrush(QPalette::Window, QBrush(_image.scaled(size(), Qt::IgnoreAspectRatio,Qt::SmoothTransformation)));
    setPalette(pal);
}

clientfile::~clientfile()
{
    delete ui;
}

void clientfile::on_connect_clicked()
{
    //获取服务器的ip和端口
    QString ip=ui->IPtext->text();
    qint16 port=ui->porttext->text().toInt();
    tcpsocket->connectToHost(QHostAddress(ip),port);
}

